<!--字典类型-->

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="用户名" prop="name">
          <el-input
            v-model="queryParams.username"
            placeholder="请输入用户名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="标签" prop="name">
          <el-input
            v-model="queryParams.tag"
            placeholder="请输入标签"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery()"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="handleResetQuery()"
            ><i-ep-refresh />重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button
              v-hasPerm="['sys:dict_type:add']"
              type="success"
              @click="openDialog()"
              ><i-ep-plus />新增</el-button
            >
            <el-button
              type="danger"
              :disabled="ids.length === 0"
              @click="handleDelete()"
              ><i-ep-delete />删除</el-button
            >
          </div>
          <div>
            <el-dropdown>
              <el-button type="primary">
                导入<el-icon class="el-icon--right"
                  ><i-ep-arrow-down
                /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="downloadTemplate">
                    <i-ep-download />下载模板</el-dropdown-item
                  >
                  <el-dropdown-item @click="importDialog = true">
                    <i-ep-top />导入数据</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button class="ml-3" type="warning" @click="handleExport"
              ><template #icon><i-ep-download /></template>导出</el-button
            >
          </div>
        </div>
      </template>
      <el-table
        v-loading="loading"
        highlight-current-row
        :data="computerTypeList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="标签" prop="tag" width="100" />
        <el-table-column label="管理员" prop="username" width="100" />
        <el-table-column label="cpu" prop="cpu" width="100" />
        <el-table-column
          label="操作系统"
          prop="os"
          align="center"
          width="200"
        />
        <el-table-column label="显卡" prop="graphicsCard" align="center" />
        <el-table-column label="屏幕" prop="screen" align="center" />
        <el-table-column label="外部设备" prop="peripheral" align="center" />
        <el-table-column label="内存" prop="memory" align="center" />
        <el-table-column
          label="创建时间"
          prop="createTime"
          align="center"
          width="150"
        />
        <el-table-column
          label="更新时间"
          prop="updateTime"
          align="center"
          width="150"
        />
        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:dict_type:edit']"
              type="primary"
              size="small"
              @click.stop="openDialog(scope.row.id)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              v-hasPerm="['sys:dict_type:delete']"
              type="danger"
              size="small"
              @click.stop="handleDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="closeDialog"
    >
      <el-form
        :rules="rules"
        ref="dataFormRef"
        :model="formData"
        label-width="80px"
      >
        <el-form-item label="标签">
          <el-input v-model="formData.tag" placeholder="请输入标签" />
        </el-form-item>
        <el-form-item label="用户">
          <el-select
            filterable
            v-model="formData.userId"
            placeholder="请选择用户"
            style="width: 240px"
          >
            <el-option
              v-for="item in userSelectData"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="cpu">
          <el-input v-model="formData.cpu" placeholder="请输入cpu" />
        </el-form-item>
        <el-form-item label="内存">
          <el-input v-model="formData.memory" placeholder="请输入内存" />
        </el-form-item>
        <el-form-item label="系统">
          <el-select
            prop="os"
            placeholder="请选择操作系统"
            v-model="formData.os"
          >
            <el-option
              v-for="item in osList"
              :key="item.value"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="屏幕">
          <el-input v-model="formData.screen" placeholder="请输入屏幕" />
        </el-form-item>
        <el-form-item label="外设">
          <el-input v-model="formData.peripheral" placeholder="请输入外设" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="设备备注"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="importDialog">
      <!-- 用户导入表单 -->
      <el-form label-width="100px">
        <el-form-item label="Excel文件">
          <el-upload
            ref="uploadRef"
            action=""
            drag
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            :limit="1"
            :auto-upload="false"
            :file-list="importData.fileList"
            :on-change="handleFileChange"
            :on-exceed="handleFileExceed"
          >
            <el-icon class="el-icon--upload">
              <i-ep-upload-filled />
            </el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <template #tip>
              <div>xls/xlsx files</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialog = false">取消</el-button>
          <el-button type="primary" @click="handleImport"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "DictType",
  inheritAttrs: false,
});

import DictAPI from "@/api/dict";
import UserAPI from "@/api/user";
import type {
  ComputerTypeForm,
  ComputerQuery,
  AssetComputerPageVO,
} from "@/api/asset/computer/model";
import ComputerAPI from "@/api/asset/computer";
import { genFileId } from "element-plus";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<ComputerQuery>({
  pageNum: 1,
  pageSize: 10,
});

const computerTypeList = ref<AssetComputerPageVO[]>();

const dialog = reactive({
  title: "",
  visible: false,
});
const rules = {
  user: [{ required: true, message: "用户必须选择", trigger: "blur" }],
  os: [{ required: true, message: "操作系统必须选择", trigger: "blur" }],
};
const formData = reactive<ComputerTypeForm>({});

/** 查询 */
function handleQuery() {
  loading.value = true;
  ComputerAPI.getPage(queryParams)
    .then((data) => {
      computerTypeList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 重置查询
 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中  */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

const osList = ref([]);
// 用户树形数据
const userSelectData = ref([]);
/**
 * 打开字典类型表单弹窗
 *
 * @param dicTypeId 字典类型ID
 */
function openDialog(computerId?: number) {
  dialog.visible = true;
  // 获取部门下拉数据
  DictAPI.getDictOptions("os").then((data) => {
    osList.value = data;
  });

  UserAPI.list().then((data) => {
    userSelectData.value = data;
  });

  if (computerId) {
    dialog.title = "编辑电脑设备";
    ComputerAPI.getComputerForm(computerId).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增电脑设备";
  }
}

/** 字典类型表单提交 */
function handleSubmit() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = false;
      const dictTypeId = formData.id;
      if (dictTypeId) {
        ComputerAPI.updateComputer(dictTypeId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ComputerAPI.addComputer(formData)
          .then(() => {
            ElMessage.success("新增电脑成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭字典类型弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**  重置字典类型表单 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
}

/** 删除字典类型 */
function handleDelete(dictTypeId?: number) {
  const dictTypeIds = [dictTypeId || ids.value].join(",");
  if (!dictTypeIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    ComputerAPI.deleteComputerByIds(dictTypeIds).then(() => {
      ElMessage.success("删除成功");
      handleResetQuery();
    });
  });
}

const dictDataDialog = reactive({
  title: "",
  visible: false,
});

const selectedDictType = reactive({ typeCode: "", typeName: "" }); // 当前选中的字典类型
const importDialog = ref(false);
/** 下载导入模板 */
function downloadTemplate() {
  ComputerAPI.downloadTemplate().then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    );
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}
/** 导出电脑 */
function handleExport() {
  ComputerAPI.export(queryParams).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    );
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}
// 用户导入数据
const importData = reactive({
  deptId: undefined,
  file: undefined,
  fileList: [],
});
/** Excel文件 Change */
function handleFileChange(file: any) {
  importData.file = file.raw;
}
const uploadRef = ref();
/** Excel文件 Exceed  */
function handleFileExceed(files: any) {
  uploadRef.value!.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  uploadRef.value!.handleStart(file);
  importData.file = file;
}
const handleImport = () => {
  ComputerAPI.import(importData?.file).then((data) => {
    ElMessage.success("导入电脑成功");
    importDialog.value = false;
    handleResetQuery();
  });
};
onMounted(() => {
  handleQuery();
});
</script>
